package cn.itcast.web.controller;


import cn.itcast.domain.system.Module;
import cn.itcast.domain.system.User;
import cn.itcast.service.system.ModuleService;
import cn.itcast.service.system.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller
public class LoginController extends BaseController{
    @Autowired
    private UserService userService;

    @Autowired
    private ModuleService moduleService;
    /**
     *项目启动访问http://locahost:8080/index.jsp
     * index.jsp跳转location.href='login.do'
     * 处理login请求
     * 响应地址：http://locahost:8080/WEB-INF/pages/home/main.jsp
     */
    //普通的登录认证
    /*@RequestMapping("/login")
    public String login(String email,String password){
        //非空判断
        if(StringUtils.isEmpty(email) && StringUtils.isEmpty(password)){
            return "forward:login.jsp";
        }

        //根据email查询用户
        User user = userService.findByEmail(email);
        if(user != null && user.getPassword().equals(password)){
            //登录成功，跳转到main.jsp
            session.setAttribute("loginInfo",user);
            //查询用户的权限并保存，页面动态显示菜单数据
            List<Module> moduleList = moduleService.findModuleByUserId(user.getId());
            session.setAttribute("moduleList",moduleList);
            return "home/main";
        }
        else {
            request.setAttribute("error","用户名或密码错误！");
            return "forward:login.jsp";
        }

    }*/

    /*shiro的登录认证*/
    @RequestMapping("/login")
    public String login(String email,String password){
        //非空判断
        if(StringUtils.isEmpty(email) && StringUtils.isEmpty(password)){
            return "forward:login.jsp";
        }

        try {
            //创建一个token,封装用户名和密码
            AuthenticationToken token = new UsernamePasswordToken(email,password);
            //创建subject，表示当前用户
            Subject subject = SecurityUtils.getSubject();

            //shiro登录认证，执行login()方法，会自动渠道realm认证方法中（参数是封装好用户名和密码的authenticationtoken对象）
            subject.login(token);

            // 获取身份对象: subject.getPrincipal()
            // 获取的是realm中认证方法返回的对象的构造函数的第一个参数
            User user = (User) subject.getPrincipal();

            //登录认证成功
            //存储用户到session
            session.setAttribute("loginInfo",user);
            //查询登陆用户的权限 (动态菜单)
            List<Module> moduleList = moduleService.findModuleByUserId(user.getId());
            session.setAttribute("moduleList",moduleList);
            return "home/main";
        } catch (AuthenticationException e) {
            e.printStackTrace();
            //登录失败
            request.setAttribute("error","用户名或密码错误！");
            return "forward:login.jsp";
        }



    }


    //退出
    @RequestMapping("/logout")
    public String logout(){
        //先释放资源
        session.removeAttribute("loginInfo");
        //清空shiro认证信息
        SecurityUtils.getSubject().logout();
        //销毁会话
        session.invalidate();
        return "forward:login.jsp";
    }

    @RequestMapping("/home")
    public String home(){
        return "home/home";
    }
}
